package com.haidechizi.leetcode;

import java.util.ArrayList;
import java.util.List;

public class _23_合并K个排序链表 {

    public ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0) {
            return null;
        }
        int step = 1;
        while (step < lists.length) {
            for (int i = 0; i < lists.length - step; i += step * 2) {
                lists[i] = mergeTwoLists(lists[i], lists[i + step]);
            }
            step = step * 2;
        }
        return lists[0];
    }


    public ListNode mergeKLists2(ListNode[] lists) {
        if (lists == null || lists.length == 0) {
            return null;
        }
        ListNode head = lists[0];
        for (int i = 1; i < lists.length; i++) {
            head = mergeTwoLists(head, lists[i]);
        }

        return head;
    }

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null && l2 == null) {
            return null;
        }
        ListNode head = new ListNode(0);
        ListNode current = head;

        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                current.next = l1;
                l1 = l1.next;
            } else {
                current.next = l2;
                l2 = l2.next;
            }
            current = current.next;
        }

        if (l1 != null) {
            current.next = l1;
        }
        if (l2 != null) {
            current.next = l2;
        }
        return head.next;
    }

    public ListNode mergeKLists1(ListNode[] lists) {
        List<ListNode> list = new ArrayList<>();
        for (ListNode node : lists) {
            while (node != null) {
                list.add(node);
                node = node.next;
            }
        }
        list.sort((n1, n2) -> {
            return n1.val - n2.val;
        });
        ListNode head = new ListNode(0);
        ListNode current = head;
        for (ListNode node : list) {
            current.next = node;
            current = current.next;
        }
        return head.next;
    }
}
